import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

class AnimPage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<AnimPage>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  var target = 0.0;
  final Map<double, String> data = {
    0.25: "north",
    0.50: "west",
    0.75: "south",
    1.00: 'east'
  };
  
  // 用于存储延迟执行的Future，以便在dispose时取消
  Future<void>? _delayedFuture;
  
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 900),
    );
  }
  
  // 将showResult移到build外部，作为State类的方法
  void showResult(double target) {
    final snak = SnackBar(
      content: Text(
        "Pen is pointed to ${data[target]}",
        style: const TextStyle(
            fontSize: 20, fontWeight: FontWeight.w500, color: Colors.green),
      ),
      duration: const Duration(seconds: 2),
    );
    // 检查组件是否仍然存在，避免在已销毁组件上调用ScaffoldMessenger
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(snak);
    }
  }
  
  @override
  void dispose() {
    // 取消所有正在进行的Future，防止组件销毁后异步操作继续执行
    _delayedFuture?.timeout(Duration.zero, onTimeout: () {});
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: size.height,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
                top: 50,
                child: TextButton(
                    onPressed: () {},
                    child: const Text(
                      "click pen to rotate",
                      style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                    style: ButtonStyle(
                        backgroundColor: 
                            MaterialStateProperty.all(Colors.blue)))),
            Positioned(
                top: 80,
                child: TextButton(
                    onPressed: () {},
                    child: const Text(
                      "North",
                      style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                    style: ButtonStyle(
                        backgroundColor: 
                            MaterialStateProperty.all(Colors.green)))),
            Positioned(
                top: size.height * 0.48,
                left: -15,
                child: Transform.rotate(
                  angle: 190.1,
                  child: TextButton(
                      onPressed: () {},
                      child: const Text(
                        "East",
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w500,
                            color: Colors.white),
                      ),
                      style: ButtonStyle(
                          backgroundColor: 
                              MaterialStateProperty.all(Colors.green))),
                )),
            Positioned(
                top: size.height * 0.48,
                right: -15,
                child: Transform.rotate(
                  angle: -190.1,
                  child: TextButton(
                      onPressed: () {},
                      child: const Text(
                        "West",
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w500,
                            color: Colors.white),
                      ),
                      style: ButtonStyle(
                          backgroundColor: 
                              MaterialStateProperty.all(Colors.green))),
                )),
            Positioned(
                bottom: 80,
                child: TextButton(
                    onPressed: () {},
                    child: const Text(
                      "North",
                      style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                    style: ButtonStyle(
                        backgroundColor: 
                            MaterialStateProperty.all(Colors.green)))),
            AnimatedBuilder(
              animation: controller,
              child: Container(
                child: GestureDetector(
                    onTap: () {
                      setState(() {
                        controller.repeat();
                      });
                      // 存储Future引用，以便在dispose时取消
                      _delayedFuture = Future.delayed(Duration(seconds: 10), () {
                        // 添加mounted检查，防止在组件销毁后调用setState
                        if (mounted) {
                          setState(() {
                            target += 0.25;
                            controller.animateTo(target,
                                duration: Duration(seconds: 1));
                            showResult(target);
                            if (target == 1.00) {
                              target = 0.0;
                            }
                          });
                        }
                      });
                    },
                    child: Image.asset(
                      'images/penimg2.png',
                      width: size.width * 0.5,
                    ))),
              builder: (context, Widget? widget) {
                return Transform.rotate(
                  angle: controller.value * 2 * 3.14,
                  child: widget,
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
